package com.huaxin.dao.impl;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.huaxin.commons.database.ConnectionProvider;
import com.huaxin.dao.ISettingDAO;
import com.huaxin.entity.SettingEntity;
import com.huaxin.values.ConstantOfSQL;

public class SettingDAO implements ISettingDAO {
	private SQLiteDatabase sqlDB;

	public SettingDAO(ConnectionProvider connectionProvider) {
		sqlDB = connectionProvider.getSQLiteDatabase();
	}

	@Override
	public SettingEntity queryOneByField(String fieldName) {
		SettingEntity settingEntity = null;
		Cursor cursor = sqlDB.query(ConstantOfSQL.TABLE_SETTING,
				ConstantOfSQL.TABLE_SETTING_COLNUMS,
				ConstantOfSQL.TABLE_SETTING_COLNUMS[1] + "=?",
				new String[] { fieldName }, null, null, null, null);
		while (cursor.moveToNext()) {
			settingEntity = new SettingEntity();
			settingEntity.setId(cursor.getInt(cursor
					.getColumnIndex(ConstantOfSQL.TABLE_SETTING_COLNUMS[0])));
			settingEntity.setField(cursor.getString(cursor
					.getColumnIndex(ConstantOfSQL.TABLE_SETTING_COLNUMS[1])));
			settingEntity.setValue(cursor.getString(cursor
					.getColumnIndex(ConstantOfSQL.TABLE_SETTING_COLNUMS[2])));
		}
		return settingEntity;
	}

	@Override
	public void updateSetting(String fieldName, String value) {
		ContentValues values = new ContentValues();
		values.put(ConstantOfSQL.TABLE_SETTING_COLNUMS[2], value);
		try {
			sqlDB.beginTransaction();
			sqlDB.update(ConstantOfSQL.TABLE_SETTING, values,
					ConstantOfSQL.TABLE_SETTING_COLNUMS[1] + "=?",
					new String[] { fieldName });
			sqlDB.setTransactionSuccessful();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			sqlDB.endTransaction();
		}

	}

}
